package com.itheima.service;

import com.itheima.client.OrderClient;
import com.itheima.cloud.pojo.User;
import com.itheima.cloud.response.OrderVO;
import com.itheima.cloud.response.UserOrderVo;
import com.itheima.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderClient orderClient;

    @Autowired
    Mapper mapper;

    public User findUserById(String username) {
        if (StringUtils.isEmpty(username)){
            throw new RuntimeException("非法请求");
        }

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        List<User> users = userMapper.selectByExample(example);
        return users.get(0);
    }

    public UserOrderVo findOrderByUserName(String username) {
        //校验
        if (StringUtils.isEmpty(username)){
            throw new RuntimeException("非法请求");
        }

        User user = findUserById(username);
        if (user == null) {
            throw new RuntimeException("非法请求");
        }

        //远程调用order微服务,获取订单的列表
        List<OrderVO> orderList = orderClient.findOrderByUsername(username);

        if (orderList == null){
            orderList = new ArrayList<>();
        }

        //封装返回结果集
        UserOrderVo userOrderVo = new UserOrderVo();
        userOrderVo.setUsername(user.getUsername());
        userOrderVo.setOrderlist(orderList);


        return userOrderVo;
    }
}
